//
//  AppDelegate.swift
//  M4
//
//  Created by YuChuang on 2024/8/6.
// com.applesimple

import UIKit
import IQKeyboardManagerSwift
import Alamofire
import AdjustSdk
import FacebookCore
import AppTrackingTransparency
import FirebaseCore   // 这是 FirebaseApp.configure() 所在模块
import FirebaseCrashlytics
import FirebaseAnalytics
//import FirebaseAuth

import Toast_Swift
@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        FirebaseApp.configure()
        ApplicationDelegate.shared.application(
            application,
            didFinishLaunchingWithOptions: launchOptions
        )
        Settings.shared.isAdvertiserIDCollectionEnabled = true

        M4SetWindow()
        if M4FirstEnterApp() {
            M4DeviceDataManager.m4DeviceShare.m4firstEnterTime = Int(Date().timeIntervalSince1970)
        }
        M4DeviceDataManager.m4DeviceShare.m4SSq = 0
//        M4SetAdjust()
        UIButton.initializeMethod()
        M4SetKeyboard()
        M4CheckNetwork()
        M4PublicNetwork.M4GetAppConfigNet()
       
        
      
        return true
    }
    
    func applicationDidBecomeActive(_ application: UIApplication) {
        M4DeviceDataManager.m4DeviceShare.m4SSq += 1
        
        M4LocationVerification.getLocation()
        
        M4GetAdjustData()
    }
    

    private func M4SetWindow() {
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.backgroundColor = .white
        let vc = M4LaunchViewController()
//        vc.animaComplete = {
//            self.window?.rootViewController = M4TabBarViewController()
//        }
        window?.rootViewController = vc
        window?.makeKeyAndVisible()
    }
    
    func M4SetAdjust() {
        
        /* 如果您要记录设备的广告主 ID (即 IDFA)，需要先展示弹窗获得用户的授权。 */
        Adjust.requestAppTrackingAuthorization { status in
            let adjustToken = "8yj6r0t9xlvk"
            let envir = ADJEnvironmentProduction
            let config = ADJConfig(appToken: adjustToken, environment: envir)
            config?.attConsentWaitingInterval = 5
            config?.logLevel = .verbose
            Adjust.initSdk(config)
            
            
            self.M4GetAdjustData()
        }
    }
    
    private func M4GetAdjustData() {
        Adjust.idfa(completionHandler: { idfa in
            M4UserDataManager.m4UserShare.adjustIdfa = idfa ?? ""
        })
        
        Adjust.idfv(completionHandler: { idfv in
            M4UserDataManager.m4UserShare.adjustIdfv = idfv ?? ""
        })
        
//        if [1, 2].contains(Adjust.appTrackingAuthorizationStatus()) { return }
        Adjust.adid(completionHandler: { adid in
            M4UserDataManager.m4UserShare.adjustAdid = adid ?? ""
        })
    }
    
    private func M4SetKeyboard() {
        IQKeyboardManager.shared.enable = true
        IQKeyboardManager.shared.enableAutoToolbar = true
        IQKeyboardManager.shared.shouldResignOnTouchOutside = true
        IQKeyboardManager.shared.toolbarDoneBarButtonItemText = "Done"
        IQKeyboardManager.shared.toolbarTintColor = .lightGray
        IQKeyboardManager.shared.keyboardDistanceFromTextField = 5.0
    }
    
    private func M4FirstEnterApp() -> Bool {
        let userDefaults = UserDefaults.standard
        var number = userDefaults.integer(forKey: "M4FirstEnterApp")
        if number > 0 {
            number += 1
            userDefaults.set(number, forKey: "M4FirstEnterApp")
            userDefaults.synchronize()
            return false
        }
        else {
            userDefaults.set(1, forKey: "M4FirstEnterApp")
            userDefaults.synchronize()
            return true
        }
    }

}


extension AppDelegate {
    
    public static func keyWindow() -> UIWindow? {
        var window: UIWindow?
        if #available(iOS 13.0, *) {
            window = UIApplication.shared.connectedScenes
                .filter({$0.activationState == .foregroundActive})
                .map({$0 as? UIWindowScene})
                .compactMap({$0})
                .first?.windows
                .filter({$0.isKeyWindow}).first
        }
        
        if window == nil {
            window = UIApplication.shared.windows.first { $0.isKeyWindow }
            if window == nil {
                window = UIApplication.shared.keyWindow
            }
        }
        
        if window == nil {
            window = UIApplication.shared.delegate?.window ?? nil
        }
        
        return window
    }
    
    static func M4JumpLoginPage() {
        let vc = M4LoginViewController()
        let nav = M4UINavigationController(rootViewController: vc)
        AppDelegate.keyWindow()?.rootViewController = nav
//        AppDelegate.keyWindow()?.insertSubview(nav.view, at: 0)
    }
    
    func M4CheckNetwork() {
         NetworkReachabilityManager.default?.startListening(onUpdatePerforming: { status in
             var netAlert: M4NetworkAlertView?
             if status == .notReachable{
//                 M4DeviceDataManager.m4DeviceShare.m4XwMAiX = "unknown"
//                 netAlert = UINib(nibName: "M4NetworkAlertView", bundle: nil).instantiate(withOwner: self).last as? M4NetworkAlertView
//                 netAlert?.M4NetworkAlertShow()
                 DispatchQueue.main.async {
                     M4NetworkAlertView.shared.showOnce()
                 }
             }
             else {
                 if status == .reachable(.cellular) {
                     M4DeviceDataManager.m4DeviceShare.m4XwMAiX = "cellular"
                 }
                 else if status == .reachable(.ethernetOrWiFi) {
                     M4DeviceDataManager.m4DeviceShare.m4XwMAiX = "WIFI"
                 } else {
                     M4DeviceDataManager.m4DeviceShare.m4XwMAiX = "unknown"
                 }
             }
         })
     }
    
}

